#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "stu.h"

void initStuArr(Stu_t arr[], int len){
	srand((unsigned)time(NULL));
	for(int i=0;i<len;i++){
		sprintf(arr[i].name,"%d%d%d",i,i,i);
		arr[i].id=i;
		arr[i].chinese=rand()%101;
		arr[i].math=rand()%101;
		arr[i].english=rand()%101;
		arr[i].physical=rand()%101;
		arr[i].biological=rand()%101;
		arr[i].chemical=rand()%101;
	}
}

static void printOneStu(Stu_t stu){
	printf("%s\t%d\t%.1lf\t%.1lf\t%.1lf\t%.1lf\t%.1lf\t%.1lf\n", stu.name,stu.id,
			stu.chinese,stu.math,stu.english,stu.physical,
			stu.biological,stu.chemical);
}

static void printTitle(){
	printf("姓名\t学号\t语文\t数学\t英语\t物理\t生物\t化学\n");
}

void printStuArr(Stu_t arr[],int len){
	printTitle();
	for(int i=0;i<len;i++){
		printOneStu(arr[i]);
	}
}

int saveStu(Stu_t arr[],int len, char* filename){
	FILE *fp=fopen(filename,"w");
	if(fp==NULL){
		perror("数据存储时发生异常，文件未能打开");
		return -1;
	}
	for(int i=0;i<len;i++){
		Stu_t stu=arr[i];
		fprintf(fp,"%s\t%d\t%.1lf\t%.1lf\t%.1lf\t%.1lf\t%.1lf\t%.1lf\n", stu.name,stu.id,
			stu.chinese,stu.math,stu.english,stu.physical,
			stu.biological,stu.chemical);
	}
	fclose(fp);
}

int loadStu(char* filename){
	FILE *fp=fopen(filename, "r");
	if(fp==NULL){
		perror("数据读取时发生异常，文件未能打开");
		return -1;
	}
	printTitle();
	Stu_t stu;
	while(1){
		int ret=fscanf(fp,"%s\t%d\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf",stu.name,&stu.id,
				&stu.chinese,&stu.math,&stu.english,&stu.physical,&stu.biological,
				&stu.chemical);
		printOneStu(stu);
		if(ret == EOF)
			break;
	}
	fclose(fp);
}
